<?php
declare (strict_types=1);

namespace app\command;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class Mq extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('mq')
            ->setDescription('the mq command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 队列名 消息队列载体，每个消息都会被投入到一个或多个队列
        $queue = 'hello';

        // 建立连接
        $connection = new AMQPStreamConnection('127.0.0.1', '5672', 'guest', 'guest', '/');
        // 获取信道
        $channel = $connection->channel();
        // 声明创建队列
        $channel->queue_declare($queue, false, false, false, false);

        // 消息消费
        $channel->basic_consume($queue, '', false, true, false, false, function ($msg) use ($output) {
            $output->writeln('received:' . $msg->body . PHP_EOL);
        });

        while (count($channel->callbacks)) {
            $channel->wait();
        }

        // 关闭信道
        $channel->close();
        // 关闭连接
        $connection->close();
    }
}
